import routes from "../route/route";
import mongodbHandle from '../handle/mongodbHandle';
import rankHandle from '../handle/rankHandle';
const jwt = require('jsonwebtoken');
var ObjectId = require('mongodb').ObjectId;
import * as moment from 'moment'
import app from '../app';
import utils from '../serverCore/utils';
import redisHandle from 'src/handle/redisHandle';
import * as request from 'request'
import { base64 } from '../serverCore/enco';
import { PlayerModel } from "src/core/model/playerModel";
import { gameConfigHandle } from "core/config/gameConfig";

var utility = require("utility");

function getResData(data) {
    data = JSON.stringify(data)
    if (app.env == 'pro' || app.env == "demo") {
        data = base64.encode(data)
    }
    return data
}

routes.setUserNotLogin('adminRegister', [
    ['name', 'string'],
    ['pwd', 'string']
], async (msg, session,) => {
    let name = msg.name
    let pwd = msg.pwd
    console.log(app.env)
    if (app.env == "adminDemo") {
        let doc = await mongodbHandle.userAdminDao.findOne({ name, pwd })

        if (doc) {
            return { err: 1 }
        } else {
            await mongodbHandle.userAdminDao.newAndSave(name, pwd)
            return { err: 0 }
        }
    } else {
        return { err: 2 }
    }

})


routes.setUserNotLogin('adminLogin', [
    ['name', 'string'],
    ['pwd', 'string']
], async (msg, session,) => {
    let name = msg.name
    let pwd = msg.pwd

    let doc = await mongodbHandle.userAdminDao.findOne({ name, pwd })
    console.log(doc)
    if (doc) {
        let token = jwt.sign({
            name: name,
            pwd: pwd
        }, "secretkey", {
            expiresIn: '2day'
        })
        return { err: 0, data: token }
    } else {
        return { err: 1 }
    }
})

routes.setUserNotLogin('getBakPlayer', [
    ['id', 'string'],
    ['index', 'number']
], async (msg) => {
    let playerDoc =  await mongodbHandle.playerDao.findOne({id:msg.id})
    if(!playerDoc){
        return { err: 0 }
    }
    let doc = await mongodbHandle.playerBakDao.findOne({
        pID: playerDoc._id.toString(),
    })
    if (doc) {
        let data = {
            ['playerData' + msg.index] : doc['playerData' + msg.index],
            [msg.index]: doc[msg.index],
        }
        return { err: 0, data: data }
    } else {
        return { err: 0 }
    }
})

routes.setUserNotLogin('getPlayerBaseInfo', [
    ['pID', 'string'],
], async (msg, session, cb) => {
    let id
    try {
        id = ObjectId(msg.pID)
    } catch (error) {
        return { err: 0, code: 1 }
    }
    let doc = await mongodbHandle.playerDao.findOne({
        _id: id
    })
    if (doc) {
        return {
            err: 0, data: {
                name: doc.name,
                currentServerID: doc.currentServerID,
                chargeMoney: doc.chargeMoney,
            }
        }
    } else {
        return { err: 0, code: 1 }
    }
})

routes.setUserNotLogin('getPlayer', [
    ['pID', 'string'],
], async (msg, session, cb) => {
    let id
    try {
        id = ObjectId(msg.pID)
    } catch (error) {
        return { err: 0, code: 1 }
    }
    let doc = await mongodbHandle.playerDao.findOne({
        _id: id
    })
    if (doc) {
        return {
            err: 0, data: {
                name: doc.name,
                currentServerID: doc.currentServerID,
                chargeMoney: doc.chargeMoney,
            }
        }
    } else {
        return { err: 0, code: 1 }
    }
})

routes.setUserNotLogin('getPlayerData', [
    ['id', 'string'],
], async (msg, session, cb) => {
    let id = msg.id
    let doc = await mongodbHandle.playerDao.findOne({
        id: id
    })
    if (doc) {
        return {
            err: 0, data: doc
        }
    } else {
        return { err: 0, code: 1 }
    }
})


routes.setUserNotLogin('giftBuyTims', [
    ['pID', 'string'],
], async (msg, session) => {
    let {
        pID
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(pID),
    })
    if (doc) {
        return {
            err: 0, data: {
                giftTime: doc.giftTime || moment().startOf('day').valueOf(),
                giftBuyTims: doc.giftBuyTims || 0
            }
        }
    }
    return {
        err: 0, data: {
            giftTime: 0,
            giftBuyTims: 0
        }
    }
})

routes.setLogin('getUserList', [
    ['page', 'number'],
    ['pageSize', 'number']
], async (msg, session, cb) => {
    let {
        page,
        pageSize
    } = msg
    let query = {}
    let count = await mongodbHandle.userDao.count(query)
    let docs = await mongodbHandle.userDao.findByPage(query, (page - 1) * pageSize, pageSize)
    return { err: 0, data: { data: docs, total: count } }
})

routes.setLogin('getPlayerListByName', [
    ['name', 'string'],
], async (msg, session, cb) => {
    let {
        name
    } = msg
    let query = {
        name: name
    }
    let docs = await mongodbHandle.playerDao.find(query)
    for (let i = 0; i < docs.length; i++) {
        let item = docs[i]
        item.Diamond = item.playerData.BasicInfo.Diamond
        item.Gold = item.playerData.BasicInfo.Gold
        item.PlayerLvl = []
        if (item.playerData.Team) {
            item.playerData.Team.forEach(e => {
                if (e) {
                    item.PlayerLvl.push(e.Lvl)
                }
            })
        }

        delete item.playerData
    }
    return { err: 0, data: docs }
})

routes.setLogin('getPlayerList', [
    ['page', 'number'],
    ['pageSize', 'number'],
    ['serverID', 'number', false],
    ['isCharge', 'boolean', false],
], async (msg, session, cb) => {
    let {
        page,
        pageSize,
        isCharge,
        serverID
    } = msg
    let query = {
        cheat: false,
        currentServerID: serverID
    }
    if (isCharge) {
        query['chargeMoney'] = { $gt: 0 }
    }
    let sortQuery = {
        totalPower: -1
    }
    let count = await mongodbHandle.playerDao.count(query)
    let docs = await mongodbHandle.playerDao.findByPageAndSort(query, { mapProgressMax: -1 }, (page - 1) * pageSize, pageSize)
    for (let i = 0; i < docs.length; i++) {
        let item = docs[i]
        let player = new PlayerModel(item.playerData)
        item.itemInfo = player.itemInfo
        item.useInfo = player.useInfo
        item.bag = player.bag.items
        delete item.playerData
        let userData = await mongodbHandle.userDao.findOne({ _id: ObjectId(item.uID) })
        item.userName = userData.name
    }
    return { err: 0, data: { data: docs, total: count } }
})

routes.setLogin('getPlayerCheatList', [
    ['page', 'number'],
    ['pageSize', 'number'],
    ['serverID', 'number', false],
], async (msg, session, cb) => {
    let {
        page,
        pageSize,
        totalPower,
        serverID
    } = msg
    let query = {
        currentServerID: serverID,
        "playerData.BaseInfo.InfoFlag": 1
    }
    let sortQuery = {
        totalPower: -1
    }
    let count = await mongodbHandle.playerDao.count(query)
    let docs = await mongodbHandle.playerDao.findByPageAndSort(query, { mapProgressMax: -1 }, (page - 1) * pageSize, pageSize)
    for (let i = 0; i < docs.length; i++) {
        let item = docs[i]
        let player = new PlayerModel(item.playerData)
        item.Diamond = player.itemInfo.diamond
        item.VipExp = player.itemInfo.vipExp
        item.Gold = player.itemInfo.gold
        item.UseInfo = player.useInfo
        delete item.playerData
        let userData = await mongodbHandle.userDao.findOne({ _id: ObjectId(item.uID) })
        item.userName = userData.name
    }
    return { err: 0, data: { data: docs, total: count } }
})

routes.setLogin('getPlayer', [
    ['pID', 'string'],
], async (msg, session, cb) => {
    let doc = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(msg.pID)
    })
    if (doc) {
        doc.Gold = doc.playerData.BasicInfo.Gold
        doc.Diamond = doc.playerData.BasicInfo.Diamond
        delete doc.playerData
        let userData = await mongodbHandle.userDao.findOne({
            _id: ObjectId(doc.uID)
        })
        doc.uHidePay = userData.hidePay
        doc.userName = userData.name
        doc.pwd = userData.pwd

        return { err: 0, data: doc }
    } else {
        return { err: 0, code: 1 }
    }
})

routes.setLogin('getPlayerInfo', [
    ['pID', 'string'],
], async (msg, session, cb) => {
    let doc = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(msg.pID)
    })
    if (doc) {
        doc.Gold = doc.playerData.baseInfo.gold
        doc.Diamond = doc.playerData.baseInfo.diamond
        doc.itemInfo = doc.playerData.itemInfo
        doc.useInfo = doc.playerData.useInfo
        delete doc.playerData
        let userData = await mongodbHandle.userDao.findOne({
            _id: ObjectId(doc.uID)
        })
        console.log(doc)
        doc.uHidePay = userData.hidePay
        doc.userName = userData.name
        doc.pwd = userData.pwd
    }
    return { err: 0, data: doc }
})

routes.setLogin('getPlayerInfoByid', [
    ['id', 'string'],
], async (msg, session, cb) => {
    let doc = await mongodbHandle.playerDao.findOne({
        id: msg.id
    })
    if (doc) {
        doc.itemInfo = doc.playerData.itemInfo
        doc.useInfo = doc.playerData.useInfo
        delete doc.playerData
        let userData = await mongodbHandle.userDao.findOne({
            _id: ObjectId(doc.uID)
        })
        doc.uHidePay = userData.hidePay
        doc.userName = userData.name
        doc.pwd = userData.pwd
    }
    return { err: 0, data: doc }
})

routes.setLogin('getPlayerBak', [
    ['pID', 'string'],
], async (msg, session, cb) => {
    console.log(msg.pID)
    let doc = await mongodbHandle.playerBakDao.findOne({
        pID: msg.pID
    })
    for(let i = 0; i <= 24; i++){
        delete doc[`playerData${i}`]
    }
    return { err: 0, data: doc }
})

routes.setLogin('copyUserBakData', [
    ['pID', 'string'],
    ['copyID', 'string'],
    ['index', 'number']
], async (msg, session, cb) => {
    let playerData = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(msg.pID)
    })
    if (!playerData) {
        return { err: 1 }
    }
    let copyDatas = await mongodbHandle.playerBakDao.findOne({
        pID: msg.copyID
    })
    if (!copyDatas) {
        return { err: 2 }
    }
    let copyData = copyDatas[`playerData${msg.index}`]
    if (!copyData) {
        return { err: 3 }
    }

    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(msg.pID),
    }, {
        $set: {
            playerData: copyData,
            loginTime: new Date().getTime(),
            saveTime: new Date().getTime(),
        }
    })
    return { err: 0 }
})

routes.setLogin('copyUserData', [
    ['pID', 'string'],
    ['copyID', 'string'],
], async (msg, session, cb) => {
    let playerData = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(msg.pID)
    })
    if (!playerData) {
        return { err: 1 }
    }
    let copyData = await mongodbHandle.playerDao.findOne({
        pID: ObjectId(msg.copyID)
    })
    if (!copyData) {
        return { err: 2 }
    }

    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(msg.pID),
    }, {
        $set: {
            playerData: copyData.playerData,
        }
    })
    return { err: 0 }
})


routes.setLogin('setPlayerCheat', [
    ['pID', 'string'],
    ['cheat', 'boolean']
], async (msg, session) => {
    let {
        pID,
        cheat
    } = msg
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (myData) {
        await mongodbHandle.playerDao.updateOne({
            _id: ObjectId(pID)
        }, {
            $set: {
                cheat: cheat
            }
        })
    }
    return { err: 0 }
})

routes.setLogin('setPlayerInner', [
    ['pID', 'string'],
    ['inner', 'boolean']
], async (msg, session) => {
    let {
        pID,
        inner
    } = msg
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (myData) {
        await mongodbHandle.playerDao.updateOne({
            _id: ObjectId(pID)
        }, {
            $set: {
                inner: inner
            }
        })
    }
    return { err: 0 }
})

routes.setLogin('setPlayerPlatform', [
    ['pID', 'string'],
    ['accountPlatform', 'string']
], async (msg, session) => {
    let {
        pID,
        accountPlatform
    } = msg
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (myData) {
        await mongodbHandle.playerDao.updateOne({
            _id: ObjectId(pID)
        }, {
            $set: {
                accountPlatform: accountPlatform
            }
        })
    }
    return { err: 0 }
})

routes.setLogin('setPlayerKey', [
    ['pID', 'string'],
    ['key', 'string'],
    ['value', 'string']
], async (msg, session) => {
    let {
        pID,
        key, value
    } = msg
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (myData) {
        await mongodbHandle.playerDao.updateOne({
            _id: ObjectId(pID)
        }, {
            $set: {
                [key]: value
            }
        })
    }
    return { err: 0 }
})

routes.setLogin('playerModify', [
    ['pID', 'string'],
], async (msg, session) => {
    let {
        pID,
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }

    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(pID)
    }, {
        $set: {
            modify: 'init',
            modifyTimes: 0,
        }
    })
    return {
        err: 0
    }
})

routes.setLogin('addMoney', [
    ['pID', 'string'],
    ['amount', 'number'],
], async (msg, session) => {
    let {
        pID,
        amount
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }

    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(pID)
    }, {
        $set: {
            chargeMoney: (doc.chargeMoney || 0) + amount
        }
    })
    return {
        err: 0
    }
})


routes.setLogin('setVip2', [
    ['pID', 'string'],
], async (msg, session, cb) => {
    let {
        pID,
        amount
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }


    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(pID)
    }, {
        $set: {
            vip2: !doc.vip2
        }
    })
    return {
        err: 0
    }
})

routes.setLogin('buyVip', [
    ['pID', 'string'],
    ['amount', 'number'],
], async (msg, session) => {
    let {
        pID,
        amount
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }

    let vipTime = (doc.vipTime || new Date().getTime())
    if (isNaN(vipTime)) {
        vipTime = new Date().getTime()
    }
    console.log('vipTime1', vipTime, moment().valueOf())
    if (vipTime < moment().valueOf()) {
        vipTime = moment().valueOf()
    }
    vipTime += amount * 24 * 60 * 60 * 1000
    console.log('vipTime2', vipTime)
    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(pID)
    }, {
        $set: {
            vipTime: vipTime
        }
    })
    console.log("buyVip", pID, amount, vipTime, (await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })).vipTime)
    mongodbHandle.adminRecordDao.newAndSave(session.name, "buyVip", JSON.stringify({ pID, amount }))
    return {
        err: 0
    }
})

routes.setLogin('buyYearVip', [
    ['pID', 'string'],
], async (msg, session) => {
    let {
        pID,
        amount
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }

  
    let chargeType = app.config.chargeTypes[23]
    let items = []
    for (let i = 0; i < chargeType.items.length; i++) {
        items.push(chargeType.items[i]);
    }
    await mongodbHandle.mailDao.newAndSave(pID, chargeType.name, items, [])
    let oChargeMoney = doc.chargeMoney || 0
    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(pID)
    }, {
        $set: {
            chargeMoney: oChargeMoney + (chargeType.money || 0),
            vip2: true
        }
    })

    return {
        err: 0
    }
})

routes.setLogin('addVipAmount', [
    ['pID', 'string'],
    ['amount', 'number'],
], async (msg, session, cb) => {
    let {
        pID,
        amount
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }

    let vipTime = (doc.vipTime || new Date())
    if (vipTime < moment().valueOf()) {
        vipTime = moment().valueOf()
    }
    vipTime += amount * 24 * 60 * 60 * 1000
    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(pID)
    }, {
        $set: {
            vipTime: vipTime
        }
    })
    return {
        err: 0
    }
})

routes.setLogin('addClientLocalTime', [
    ['pID', 'string'],
    ['hour', 'number'],
], async (msg, session) => {
    let {
        pID,
        hour
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }

    let clientLocalTime = (doc.clientLocalTime || new Date().getTime())
    if (isNaN(clientLocalTime)) {
        clientLocalTime = new Date().getTime()
    }
    if (clientLocalTime < moment().valueOf()) {
        clientLocalTime = moment().valueOf()
    }
    clientLocalTime += hour * 1 * 60 * 60 * 1000
    if (hour == 0) {
        clientLocalTime = new Date().getTime() - 10000
    }
    await mongodbHandle.playerDao.updateOne({
        _id: ObjectId(pID)
    }, {
        $set: {
            clientLocalTime: clientLocalTime
        }
    })
    return {
        err: 0
    }
})


routes.setLogin('setGameClientData', [
    ['key', 'string'],
    ['value', 'string', false],
], async (msg, session, cb) => {
    let { key, value, env } = msg
    let str = await redisHandle.get(app.config.gameName + 'gameSet')
    let data = {}
    if (str) {
        try {
            data = JSON.parse(str)
        } catch (e) {
            data = {}
        }
    }
    if (value && value.length !== 0) {
        data[key] = value
    } else {
        delete data[key]
    }
    await redisHandle.set(app.config.gameName + 'gameSet', JSON.stringify(data))


    return {
        err: 0,
        data: data
    }
})



routes.setLogin('setServerState', [
    ['serverState', 'number'],
    ['stateText', 'string']
], async (msg, cb) => {
    app.serverState = msg.serverState
    app.stateText = msg.stateText || "服务器在维护中"
    await mongodbHandle.gameDao.updateOne({
        index: 1
    }, {
        $set: {
            serverState: app.serverState,
            stateText: app.stateText
        }
    });
    console.log(msg.serverState, msg.stateText)
    request.post({
        url: `http://127.0.0.1:${app.config.serverMasterPort}/masterapp/api/setServerState`,
        headers: {
            "testclient": "cheat123",
        },
        body: getResData({ serverState: app.serverState, stateText: app.stateText }),
    },
        function (error, response, body) {
            console.log(error, body)
        }
    );
    return { err: 0 }
})

routes.setLogin('compensateAllServer', [
    ['name', 'string'],
    ['items', 'object'],
], async (msg, session, cb) => {
    console.log("全服补偿开始", msg)
    let docs = await mongodbHandle.serverDao.find({
        active: true
    })
    let serverList = {}
    for (let i = 0; i < docs.length; i++) {
        let serverID = docs[i].newServerID
        serverList[serverID] = true
    }
    let servers: number[] = []
    Object.keys(serverList).forEach((item, i) => {
        servers[i] = Number(item)
    })

    for (let i = 0; i < servers.length; i++) {
        let serverID = servers[i]
        let page = 0
        let length = 200
        while (length >= 200) {
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: Number(serverID),

            }, { loginTime: 1 }, page * 200, 200)
            length = docs.length
            page += 1
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let pID = doc._id.toString()

                await mongodbHandle.mailDao.newAndSave(pID, msg.name, msg.items, null)
                if (i % 20 == 0) {
                    await utils.setTimeout(150)
                }
            }
            console.log(serverID, page)
        }
        console.log("服务器", serverID)
    }
    console.log("全服补偿完成")
    return {
        err: 0
    }
})

routes.setLogin('getItemList', [
], async (msg, session, cb) => {
    let items = {}
    Object.entries(gameConfigHandle.gameConfig.item).forEach(([key, value]) => {
        items[key] = value.name
    })
    Object.entries(gameConfigHandle.gameConfig.items).forEach(([key, value]: [string, any]) => {
        if (value.subType < 50) {
            items[key] = value.name
        }
    })
    return {
        err: 0, data: items
    }
})

routes.setLogin('addItem', [
    ['pID', 'string'],
    ['itemID', 'string'],
    ['value', 'number'],
], async (msg, session, cb) => {
    let {
        pID,
        itemID,
        value
    } = msg
    try {
        let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
        if (!doc) {
            return { err: 1 }
        }
        await mongodbHandle.mailDao.newAndSave(pID, '礼包', [[itemID, value]], null)
        return {
            err: 0
        }
    } catch (error) {
        return { err: 1 }
    }

})

routes.setLogin('addItem2', [
    ['pID', 'string'],
    ['items', 'object'],
], async (msg, session, cb) => {
    let {
        pID,
        items
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }
    await mongodbHandle.mailDao.newAndSave(pID, '礼包', null, items)
    return {
        err: 0
    }
})

routes.setLogin('addItem3', [
    ['pID', 'string'],
    ['name', 'string', false],
    ['items', 'object'],
    ['items2', 'object'],
], async (msg, session, cb) => {
    let {
        pID,
        items, items2, name
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }
    await mongodbHandle.mailDao.newAndSave(pID, name || '礼包', items, items2)
    return {
        err: 0
    }
})

routes.setLogin('getCumulativeRecharge', [

], async (msg, session, cb) => {

    return {
        err: 0, data: app.config.cumulativeRecharge
    }
})

routes.setLogin('setCumulativeRecharge', [
    ['pID', 'string'],
    ['money', 'string'],
    ['len', 'number'],
], async (msg, session, cb) => {
    let {
        pID,
        money, len
    } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }
    doc.cumulativeRecharge = doc.cumulativeRecharge || {}
    if (doc.cumulativeRecharge[money]) {
        delete doc.cumulativeRecharge[money]
    } else {
        doc.cumulativeRecharge[money] = len
    }
    await mongodbHandle.playerDao.updateOne({ _id: ObjectId(pID) }, { $set: { cumulativeRecharge: doc.cumulativeRecharge } })
    return {
        err: 0
    }
})

routes.setLogin('addGiftByID', [
    ['id', 'string']
], async (msg, session, cb) => {
    let { id } = msg
    let doc = await mongodbHandle.giftDao.findOne({ id: id })
    if (!doc) {
        return { err: 1 }
    }
    let idStr = utils.randomString(12)
    await mongodbHandle.giftListDao.newAndSave(idStr, id)
    return {
        err: 0,
        data: idStr,
    }
})

routes.setLogin('addGift', [
    ['id', 'string'],
    ['name', 'string'],
    ['items1', 'array', false],
    ['items2', 'array', false],
    ['endtime', 'number'],
    ['starttime', 'number'],
    ['multiple', 'boolean', false]
], async (msg, session, cb) => {
    let { id, name, diamond, items2, items1, endtime, starttime, multiple } = msg
    let doc = await mongodbHandle.giftDao.findOne({ id: id })
    if (doc) {
        return { err: 1 }
    }
    await mongodbHandle.giftDao.newAndSave(id, name, items1, items2, starttime, endtime, multiple)
    return {
        err: 0
    }
})

routes.setLogin('giftList', [
    ['page', 'number'],
    ['pageSize', 'number'],
], async (msg, session, cb) => {
    let {
        page,
        pageSize
    } = msg
    let query: any = {}
    let count = await mongodbHandle.giftDao.count(query)
    let docs = await mongodbHandle.giftDao.findByPageAndSort(query, {
        time: -1
    }, (page - 1) * pageSize, pageSize)
    return {
        err: 0, data: {
            data: docs,
            total: count,
        }
    }
})

routes.setLogin('editGiftTime', [
    ['id', 'string'],
    ['name', 'string'],
    ['items1', 'array', false],
    ['items2', 'array', false],
    ['endtime', 'number'],
    ['starttime', 'number'],
    ['multiple', 'boolean', false]
], async (msg, session, cb) => {
    let { id, name, diamond, items2, items1, endtime, starttime, multiple } = msg
    if (starttime > endtime) {
        return { err: 1 }
    }
    await mongodbHandle.giftDao.updateOne({ id: id }, { $set: { name, items1, items2, starttime, endtime, multiple } })
    return {
        err: 0
    }
})

routes.setLogin('editServerData', [
    ['_id', 'string'],
    ['serverID', 'string'],
    ['name', 'string'],
    ['time', 'number'],
], async (msg, session, cb) => {
    let { _id, serverID, name, time } = msg

    await mongodbHandle.serverDao.updateOne({ _id: ObjectId(_id) }, { $set: { serverID, name, time } })
    return {
        err: 0
    }
})

routes.setLogin('giftActive', [
    ['id', 'string'],
    ['active', 'boolean'],
], async (msg, session, cb) => {
    let { id, active } = msg
    await mongodbHandle.giftDao.updateOne({ id: id }, { $set: { active: active } })
    return {
        err: 0
    }
})


routes.setLogin('creatGifts', [
    ['id', 'string'],
    ['amount', 'number']
], async (msg, session, cb) => {
    let { id, amount } = msg
    let doc = await mongodbHandle.giftDao.findOne({ id: id })
    if (!doc) {
        return { err: 1 }
    }
    let ids = []
    for (let i = 0; i < amount; i++) {
        let idStr = utils.randomString(12)
        await mongodbHandle.giftListDao.newAndSave(idStr, id)
        ids.push(idStr)
    }

    return {
        err: 0,
        data: ids,
    }
})

routes.setLogin('delGift', [
    ['id', 'string'],
], async (msg, session, cb) => {
    let { id } = msg
    await mongodbHandle.giftDao.remove({ id: id })
    return {
        err: 0
    }
})

routes.setLogin('getAllServerList', [
    ['page', 'number'],
    ['pageSize', 'number']
], async (msg, session, cb) => {
    let {
        page,
        pageSize
    } = msg
    let query = {}
    let count = await mongodbHandle.serverDao.count(query)
    let docs = await mongodbHandle.serverDao.findByPage(query, (page - 1) * pageSize, pageSize)
    return {
        err: 0, data: {
            data: docs,
            total: count
        }
    }
})


routes.setLogin('changepwd', [
    ['name', 'string'],
    ['oldPwd', 'string'],
    ['pwd', 'string']
], async (msg, session, cb) => {
    let { name, oldPwd, pwd } = msg
    let doc = await mongodbHandle.userDao.findOne({ name, pwd: oldPwd })
    if (!doc) {
        return { err: 1 }
    }
    await mongodbHandle.userDao.updateOne({ name, pwd: oldPwd }, {
        $set: { pwd: pwd }
    })
    return {
        err: 0,
    }
})

routes.setLogin('getUseInfo', [
    ['pID', 'string'],
], async (msg, session, cb) => {
    let { pID } = msg
    let doc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (!doc) {
        return { err: 1 }
    }
    let player = new PlayerModel(doc.playerData)
    return {
        err: 0,
        data: player.useInfo
    }
})

//添加服务器
routes.setLogin('addServer', [
    ['serverID', 'number'],
    ['name', 'string'],
    ['time', 'number']
], async (msg, session, cb) => {
    let {
        serverID,
        name,
        time
    } = msg
    let doc = await mongodbHandle.serverDao.findOne({
        serverID: serverID
    })
    if (!doc) {
        mongodbHandle.serverDao.newAndSave(serverID, name, time)
        return {
            err: 0
        }
    }
    return {
        err: 1
    }
})

//添加服务器
routes.setLogin('deleteMail', [
    ['id', 'string'],
], async (msg, session, cb) => {
    let {
        id
    } = msg
    let res = await mongodbHandle.mailDao.remove({
        _id: ObjectId(id)
    })
    return {
        err: res ? 0 : 1
    }
})

//邮件列表
routes.setLogin('mailList', [
    ['page', 'number'],
    ['pageSize', 'number'],
    ['from', 'number', false],
    ['to', 'number', false],
    ['serverID', 'number', false],
    ['pID', 'number', false],
], async (msg, session, cb) => {
    let {
        page,
        pageSize,
        from,
        to,
        serverID,
        pID,
    } = msg
    let query: any = {
    }
    if (from && to) {
        query.time = {
            $gte: from,
            $lt: to
        }
    } else if (from && !to) {
        query.time = {
            $gte: from
        }
    } else if (!from && to) {
        query.time = {
            $lt: to
        }
    }

    if (pID) {
        query.pID = pID
    }

    let count = await mongodbHandle.mailDao.count(query)
    console.log('count', query, count)
    let docs = await mongodbHandle.mailDao.findByPageAndSort(query, {
        time: -1
    }, (page - 1) * pageSize, pageSize)

    return {
        err: 0, data: {
            data: docs,
            total: count,
        }
    }
})

//邮件列表
routes.setLogin('rankList', [
    ['page', 'number'],
    ['pageSize', 'number'],
    ['type', 'number'],
    ['serverID', 'number'],
    ['pID', 'string', false],
    ['phone', 'string', false],
], async (msg, session, cb) => {
    let {
        page,
        pageSize,
        type,
        serverID,
        pID,
        phone,
    } = msg
    let query: any = {}
    if (serverID) {
        let pDocs = await mongodbHandle.playerDao.find({ currentServerID: serverID })
        let pIDs = []
        for (let i = 0; i < pDocs.length; i++) {
            pIDs.push(pDocs[i].id)
        }
        query.pID = { $in: pIDs }
    }
    if (pID) {
        query.pID = pID
    }
    phone = phone || ''
    let rank, count
    if (type == 0) {
        if (pID != null) {
            let pDoc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
            if (pDoc) {
                let { rank, value } = rankHandle.getPowerRankByPID(serverID, pID, phone)
                let sData = {
                    id: pDoc.id,
                    pID: pDoc._id.toString(),
                    name: pDoc.name,
                    rank: rank + 1,
                    value: value,
                }
                rank = [sData]
                count = 1
            }
        } else {
            let docs = rankHandle.getPowerRank(serverID, phone)
            count = docs.length
            rank = docs.slice((page - 1) * pageSize, page * pageSize)
        }
        return {
            err: 0, data: {
                data: rank,
                total: count,
            }
        }
    } else if (type == 1) {
        if (pID != null) {
            let pDoc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
            if (pDoc) {
                let { rank, value } = rankHandle.getArenaRankByPID(serverID, pID, phone)
                let sData = {
                    id: pDoc.id,
                    pID: pDoc._id.toString(),
                    name: pDoc.name,
                    rank: rank + 1,
                    value: value,
                }
                rank = [sData]
                count = 1
            }
        } else {
            let docs = rankHandle.getArenaRank(serverID, phone)
            count = docs.length
            rank = docs.slice((page - 1) * pageSize, page * pageSize)
        }
        return {
            err: 0, data: {
                data: rank,
                total: count,
            }
        }
    } else if (type == 2) {
        if (pID != null) {
            let pDoc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
            if (pDoc) {
                let { rank, value } = rankHandle.getMapProgressRankByPID(serverID, pID, phone)
                let sData = {
                    id: pDoc.id,
                    pID: pDoc._id.toString(),
                    name: pDoc.name,
                    rank: rank + 1,
                    value: value,
                }
                rank = [sData]
                count = 1
            }
        } else {
            let docs = rankHandle.getMapProgressRank(serverID, phone)
            console.log(docs, serverID, 'docs')
            count = docs.length
            rank = docs.slice((page - 1) * pageSize, page * pageSize)
        }
        return {
            err: 0, data: {
                data: rank,
                total: count,
            }
        }
    } else if (type == 3) {
        if (pID != null) {
            let pDoc = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
            if (pDoc) {
                let { rank, value } = rankHandle.getAbyssProgressRankByPID(serverID, pID, phone)
                let sData = {
                    id: pDoc.id,
                    pID: pDoc._id.toString(),
                    name: pDoc.name,
                    rank: rank + 1,
                    value: value,
                }
                rank = [sData]
                count = 1
            }
        } else {
            let docs = rankHandle.getAbyssProgressRank(serverID, phone)
            count = docs.length
            rank = docs.slice((page - 1) * pageSize, page * pageSize)
        }
        return {
            err: 0, data: {
                data: rank,
                total: count,
            }
        }
    } else {
        return {
            err: 1
        }
    }
})



//添加服务器
routes.setLogin('updateServer', [
    ['id', 'string'],
    ['serverID', 'number'],
    ['name', 'string']
], async (msg, session, cb) => {
    let {
        id,
        serverID,
        name
    } = msg
    mongodbHandle.serverDao.updateOne({
        _id: ObjectId(id)
    }, {
        $set: {
            serverID: serverID,
            name: name
        }
    })
})

//合并服务器
routes.setLogin('mergeServer', [
    ['server1', 'number'],
    ['server2', 'number']
], async (msg, session, cb) => {

})

//开关服务器
routes.setLogin('activationServer', [
    ['serverID', 'number'],
], async (msg, session, cb) => {
    let {
        serverID
    } = msg

    let doc = await mongodbHandle.serverDao.findOne({
        serverID: serverID
    })
    if (doc) {
        doc.active = !doc.active
        mongodbHandle.serverDao.updateOne({
            serverID: serverID
        }, { $set: { active: doc.active } })
        return {
            err: 0
        }
    }
    return {
        err: 1
    }
})

//开关服务器
routes.setLogin('deleteServer', [
    ['serverID', 'number'],
], async (msg, session, cb) => {
    let {
        serverID
    } = msg

    let doc = await mongodbHandle.serverDao.remove({
        serverID: serverID
    })
    return {
        err: 0, data: doc
    }
})

//充值
routes.setLogin('chargeList', [
    ['page', 'number'],
    ['pageSize', 'number']
], async (msg, session, cb) => {
    let {
        page,
        pageSize,
        from,
        to,
        serverID,
        pID,
    } = msg
    let query: any = {
        isPay: true
    }
    if (from && to) {
        query.time = {
            $gte: from,
            $lt: to
        }
    } else if (from && !to) {
        query.time = {
            $gte: from
        }
    } else if (!from && to) {
        query.time = {
            $lt: to
        }
    }
    if (serverID) {
        let pDocs = await mongodbHandle.playerDao.find({ currentServerID: serverID })
        let pIDs = []
        for (let i = 0; i < pDocs.length; i++) {
            pIDs.push(pDocs[i].id)
        }
        query.pID = { $in: pIDs }
    }
    if (pID) {
        query.pID = pID
    }
    let count = await mongodbHandle.chargeDao.count(query)
    let docs = await mongodbHandle.chargeDao.findByPageAndSort(query, {
        time: -1
    }, (page - 1) * pageSize, pageSize)
    if (docs.length > 0) {
        for (let i = 0; i < docs.length; i++) {
            let item = docs[i]
            let player = await mongodbHandle.playerDao.findOne({ id: item.pID })
            if (player) {
                item.playerName = player.name
                item.serverID = player.currentServer
            }
        }
    }
    return {
        err: 0, data: {
            data: docs,
            total: count,
            list: app.config.chargeTypes
        }
    }
})


routes.setLogin('testRank', [
], async (msg, session, cb) => {
    // rankHandle.createPowerRankReward()
    // rankHandle.createArenaRankReward()
    // if (app.env == 'adminDemo') {
    //     rankHandle.createMapProgressRankReward('demo')
    //     rankHandle.createWorldBossRankReward('demo')
    // } else if (app.env == 'adminPro') {
    //     rankHandle.createMapProgressRankReward('pro')
    //     rankHandle.createWorldBossRankReward('pro')
    // } else {
    //     rankHandle.createMapProgressRankReward('dev')
    //     rankHandle.createWorldBossRankReward('dev')
    // }

    return {
        err: 0,
    }
})

routes.setLogin('testRank2', [
    ['serverID', 'number'],
    ['type', 'number']
], async (msg, session, cb) => {
    let { serverID, type } = msg


})


//充值
routes.setNotLogin('charge', [
    ['trade_status', 'string'],
    ['pid', 'string', false],
    ['out_trade_no', 'string'],
    ['trade_no', 'string', false],
    ['money', 'string', false],
    ['type', 'string', false],
    ['name', 'string', false],
    ['sign', 'string', false],
    ['sign_type', 'string', false],
], async (msg, session, cb) => {
    let {
        trade_status, pid, out_trade_no, trade_no, money, type, name, sign, sign_type
    } = msg
    if (!trade_status) {
        return { err: 1 }
    }
    let doc = await mongodbHandle.chargeDao.findOne({ orderID: out_trade_no })
    if (!doc) {
        return { err: 2 }
    }
    if (doc.isPay) {
        return { err: 3 }
    }
    await mongodbHandle.chargeDao.updateOne({ orderID: out_trade_no }, {
        $set: {
            isPay: true,
        }
    })

    //********** */
    if (doc.productID == 1 || doc.productID == 2 || doc.productID == 3) {
        let player = await mongodbHandle.playerDao.findOne({ _id: ObjectId(doc.pID) })
        let time = player.vipTime
        let vipTotal = player.vipTotal
        if (!vipTotal) {
            vipTotal = 0
        }
        let amount = 1
        if (doc.productID == 1) {
            amount = 1
        } else if (doc.productID == 2) {
            amount = 3
        } else if (doc.productID == 3) {
            amount = 6
        }
        let nowTime = new Date().getTime()
        if (nowTime > time) {
            time = nowTime
            time = moment(nowTime).add(30 * amount, 'days').valueOf()
        } else {
            time = moment(time).add(30 * amount, 'days').valueOf()
        }
        await mongodbHandle.playerDao.updateOne({
            _id: ObjectId(doc.pID)
        }, {
            $set: {
                vipTime: time,
                vipTotal: vipTotal + amount
            }
        })
    }
    return { err: 0 }
})


routes.setLogin('getChargeByDay', [
    ['day', 'number'],
], async (msg, session, cb) => {
    let { day } = msg
    let data = {}
    let docs = await mongodbHandle.chargeDao.find({ isPay: true })
    if (docs.length < 1) {
        return { err: 2 }
    }
    let total = 0
    for (let i = 0; i < docs.length; i++) {
        let doc = docs[i]
        total += doc.money
    }

    return {
        err: 0,
        data: {
            day: day,
            money: total,
            times: docs.length
        }
    }
})


routes.setLogin('transferCharge', [
    ['pID1', 'string'],
    ['pID2', 'string'],
], async (msg, session, cb) => {
    let docs = await mongodbHandle.chargeDao.find({ pID: msg.pID1, isPay: true })
    if (docs.length < 1) {
        return { err: 1 }
    }
    let total = 0, vipTotal = 0, giftTotal = 0
    for (let i = 0; i < docs.length; i++) {
        let doc = docs[i]
        total += doc.money
        if (doc.productID <= 3) {
            vipTotal += doc.money
        } else {
            giftTotal += doc.money
        }
    }
    let player1 = await mongodbHandle.playerDao.findOne({ _id: ObjectId(msg.pID1) })
    if (!player1) {
        return { err: 1 }
    }
    if (player1.transferCharge) {
        return { err: 0, code: 1 }
    }

    let player2 = await mongodbHandle.playerDao.findOne({ _id: ObjectId(msg.pID2), uID: player1.uID })
    if (!player2) {
        return { err: 0, code: 3 }
    }
    if (player2.getCharge) {
        return { err: 0, code: 2 }
    }
    await mongodbHandle.playerDao.updateOne({ pID: ObjectId(msg.pID1) }, { $set: { transferCharge: total } })
    await mongodbHandle.playerDao.updateOne({ pID: ObjectId(msg.pID2) }, { $set: { getCharge: total } })
    return { err: 0 }
})

routes.setLogin('weekgiftchange', [

], async (msg, session, cb) => {
    let productID = 4
    let docs = await mongodbHandle.chargeDao.find({ productID: productID })

    let chargeType = {
        items: [['diamond', 600], [200002, 20], [200003, 20], [200032, 5]]
    }
    console.log("每周礼包调整补偿", docs.length)
    let amount = 0
    if (docs.length > 0) {
        for (let i = 0; i < docs.length; i++) {
            let doc = docs[i]
            if (!doc.compensate && doc.time < new Date('2024 11 25 2:00:00').getTime()) {
                amount += 1
                let items = []
                for (let i = 0; i < chargeType.items.length; i++) {
                    items.push(chargeType.items[i]);
                }
                await mongodbHandle.mailDao.newAndSave(doc.pID, '每周礼包调整补偿', items, [])
                await mongodbHandle.chargeDao.updateOne({ orderID: doc.orderID }, { $set: { compensate: 1 } })
            }
        }
    }
    console.log("每周礼包调整补偿结束", amount)
    return {
        err: 0,
        data: {

        }
    }
})